<!-- src/components/topology-editor/JSONImportModal.vue -->
<template>
  <n-modal
    :show="show"
    @update:show="handleUpdateShow"
    class="json-import-modal"
  >
    <n-card
      style="width: 600px"
      title="导入拓扑图"
      :bordered="false"
      size="huge"
    >
      <template #header-extra>
        <n-button
          quaternary
          circle
          @click="showFormatExample = !showFormatExample"
        >
          <template #icon>
            <n-icon><HelpCircleOutline /></n-icon>
          </template>
        </n-button>
      </template>

      <n-tabs type="line">
        <n-tab-pane name="format1" tab="完整格式">
          <n-alert title="格式说明" type="info" style="margin-bottom: 16px">
            支持 VueFlow 原生 JSON 格式，包含完整的样式和连接信息
          </n-alert>
          <n-input
            v-model:value="jsonInput"
            type="textarea"
            placeholder="粘贴完整的拓扑图 JSON 数据..."
            :rows="15"
            :class="{ 'has-error': jsonError }"
          />
        </n-tab-pane>

        <n-tab-pane name="format2" tab="简化格式">
          <n-alert title="格式说明" type="info" style="margin-bottom: 16px">
            使用简化格式，系统会自动补充样式和连接器信息
          </n-alert>
          <n-input
            v-model:value="jsonInput"
            type="textarea"
            placeholder="粘贴简化格式的拓扑图数据..."
            :rows="15"
            :class="{ 'has-error': jsonError }"
          />
          <n-collapse-transition :show="showFormatExample">
            <n-card size="small" style="margin-top: 16px">
              <template #header>简化格式示例</template>
              <pre style="font-size: 12px; margin: 0">{{
                simplifiedFormatExample
              }}</pre>
            </n-card>
          </n-collapse-transition>
        </n-tab-pane>
      </n-tabs>

      <template #footer>
        <n-space justify="end">
          <n-button @click="handleCancel">取消</n-button>
          <n-button
            type="primary"
            @click="handleImport"
            :disabled="!jsonInput.trim()"
          >
            导入
          </n-button>
        </n-space>
      </template>
    </n-card>
  </n-modal>
</template>

<script setup>
import { ref, computed, watch } from "vue";
import {
  NModal,
  NCard,
  NInput,
  NButton,
  NSpace,
  NTabs,
  NTabPane,
  NAlert,
  NCollapseTransition,
  NIcon,
} from "naive-ui";
import { HelpCircleOutline } from "@vicons/ionicons5";
import { nodeTemplates } from "../../utils/nodeTemplates";

// 定义 props 和 emits
const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["update:show", "import"]);

const jsonInput = ref("");
const jsonError = ref(false);
const showFormatExample = ref(false);

// 监听 show prop 的变化，重置表单状态
watch(
  () => props.show,
  (newVal) => {
    if (newVal) {
      // 模态框打开时重置状态
      jsonInput.value = "";
      jsonError.value = false;
    }
  }
);

const simplifiedFormatExample = computed(() => {
  return `{
  "nodes": [
    {
      "id": "flight-control-1",
      "type": "SYS-001",
      "position": { "x": 100, "y": 100 }
    },
    {
      "id": "imu-1", 
      "type": "SYS-002", 
      "position": { "x": 400, "y": 100 }
    }
  ],
  "edges": [
    {
      "source": "flight-control-1",
      "target": "imu-1",
      "sourcePin": "J1-A5",  // RS-422_POS_P
      "targetPin": "J1-3"    // RS-422_RX_P
    }
  ]
}`;
});

// 处理模态框显示状态更新
const handleUpdateShow = (value) => {
  emit("update:show", value);
};

// 处理取消
const handleCancel = () => {
  emit("update:show", false);
};

// 处理导入
const handleImport = () => {
  try {
    if (!jsonInput.value.trim()) {
      jsonError.value = true;
      return;
    }

    const topologyData = JSON.parse(jsonInput.value);
    console.log("解析的原始数据:", topologyData);

    // 判断是完整格式还是简化格式
    let importData;
    if (isSimplifiedFormat(topologyData)) {
      console.log("检测到简化格式，进行转换");
      importData = convertToFullFormat(topologyData);
    } else {
      console.log("检测到完整格式，直接使用");
      importData = topologyData;
    }

    console.log("转换后的数据:", importData);

    // 验证转换后的数据
    if (!importData.nodes || !Array.isArray(importData.nodes)) {
      throw new Error("数据转换失败：nodes 格式不正确");
    }

    // 确保传递正确的数据格式
    emit("import", importData);
    jsonInput.value = "";
    jsonError.value = false;
    emit("update:show", false);
  } catch (error) {
    jsonError.value = true;
    console.error("JSON 导入错误:", error);
    // 可以在这里添加用户提示
  }
};

// 判断是否为简化格式
const isSimplifiedFormat = (data) => {
  return (
    data.nodes &&
    data.nodes.length > 0 &&
    typeof data.nodes[0].type === "string" &&
    !data.nodes[0].data
  );
};

const calculateDynamicNodeConfig = (template) => {
  const baseWidth = 200;
  const headerHeight = 45;
  const connectorTitleHeight = 22;
  const pinRowHeight = 24;

  let totalHeight = headerHeight;

  template.connectors?.forEach((connector) => {
    totalHeight += connectorTitleHeight;
    if (connector.pins && connector.pins.length > 0) {
      totalHeight += connector.pins.length * pinRowHeight;
    }
  });

  totalHeight += 8;
  const minHeight = Math.max(140, totalHeight);

  return {
    nodeSize: {
      width: baseWidth,
      height: minHeight,
    },
  };
};

// 将简化格式转换为完整格式
const convertToFullFormat = (simplifiedData) => {
  const supportedTypes = Object.keys(nodeTemplates);

  const nodes = simplifiedData.nodes.map((node) => {
    const deviceType = node.type;

    if (!supportedTypes.includes(deviceType)) {
      const availableTypes = supportedTypes.join(", ");
      throw new Error(
        `不支持的设备类型: "${deviceType}"。当前支持的类型有: ${availableTypes}`
      );
    }

    const template = nodeTemplates[deviceType];
    const { nodeSize } = calculateDynamicNodeConfig(template);

    return {
      id: node.id,
      type: "missileDevice",
      position: node.position,
      data: {
        ...template.defaultData,
        label: template.name,
        type: deviceType,
        connectors: template.connectors,
        description: template.description,
        subsystem: template.subsystem,
      },
      style: {
        border: `2px solid ${template.color}`,
        borderRadius: "8px",
        background: "white",
        width: `${nodeSize.width}px`,
        height: `${nodeSize.height}px`,
        fontSize: "11px",
        boxShadow: "0 2px 8px rgba(0,0,0,0.1)",
      },
    };
  });

  // 修复：确保边ID唯一性
  const edges = (simplifiedData.edges || []).map((edge, index) => {
    const uniqueId = `imported-edge-${edge.source}-${
      edge.target
    }-${index}-${Date.now()}-${Math.random().toString(36).substr(2, 5)}`;

    // 获取连接颜色
    const edgeColor = getImportEdgeColor(edge, simplifiedData.nodes);

    return {
      id: uniqueId,
      source: edge.source,
      target: edge.target,
      sourceHandle: edge.sourcePin,
      targetHandle: edge.targetPin,
      style: {
        stroke: edgeColor,
        strokeWidth: 2,
      },
      type: "smoothstep",
      data: {
        sourcePin: edge.sourcePin,
        targetPin: edge.targetPin,
        color: edgeColor,
      },
    };
  });
  

  return { nodes, edges };
};

// 新增：为导入的边获取颜色
const getImportEdgeColor = (edge, nodes) => {
  const sourceNode = nodes.find(node => node.id === edge.source);
  if (sourceNode && nodeTemplates[sourceNode.type]) {
    const template = nodeTemplates[sourceNode.type];
    const pinInfo = findPinInfo(template.connectors, edge.sourcePin);
    if (pinInfo) {
      return getPinColor(pinInfo.type);
    }
  }
  return '#666';
}
</script>

<style scoped>
.json-import-modal {
  max-width: 90vw;
}

.has-error :deep(.n-input__textarea) {
  border-color: #d03050;
}

pre {
  white-space: pre-wrap;
  word-wrap: break-word;
}
</style>